package com.bdqn.tour.servlet.Hzy;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.bdqn.tour.service.impl.HzyOrdersServiceImpl;
import com.bdqn.tour.util.HzyAliPay.AlipayConfig;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/alipay/payNotify")
public class PaNotifyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置编码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        PrintWriter out = resp.getWriter();

        try {
            // 获取支付宝POST过来的信息
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = req.getParameterMap();

            for (String name : requestParams.keySet()) {
                String[] values = requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                params.put(name, valueStr);
            }
            System.out.println("收到支付宝通知：" + params);
            // 验证签名
            boolean signVerified = AlipaySignature.rsaCheckV1(
                    params,
                    AlipayConfig.ALIPAY_PUBLIC_KEY,
                    AlipayConfig.CHARSET,
                    AlipayConfig.SIGNTYPE
            );
            System.out.println("签名验证结果：" + signVerified);
            if (signVerified) {
                // 商户订单号
                String outTradeNo = params.get("out_trade_no");
                // 支付宝交易号
                String tradeNo = params.get("trade_no");
                // 交易状态
                String tradeStatus = params.get("trade_status");

                System.out.println("订单号：" + outTradeNo);
                System.out.println("交易号：" + tradeNo);
                System.out.println("交易状态：" + tradeStatus);

                // 判断交易状态
                if ("TRADE_SUCCESS".equals(tradeStatus)) {
                    // 解析订单号中的类型和ID
                    String orderType = outTradeNo.substring(0, 1);
                    String orderId = outTradeNo.substring(1);

                    // 目前只处理酒店订单
                    if ("H".equals(orderType)) {
                        boolean updated = new HzyOrdersServiceImpl().updateHotelPayStatus(orderId, "已支付");
                        System.out.println("更新订单支付状态：" + updated);
                        if (updated) {
                            // 返回 success 给支付宝，避免重复通知
                            out.println("success");
                            return;
                        }
                    }
                }
            }

            // 验证失败或更新失败，返回 fail 让支付宝重试
            out.println("fail");

        } catch (AlipayApiException e) {
            // 处理异常情况
            out.println("fail");
            e.printStackTrace();
        } finally {
            out.flush();
            out.close();
        }
    }
}
